package com.cweb.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.cweb.framework.pojo.BaseResponse;
import com.cweb.framework.pojo.CustomException;
import com.cweb.framework.util.HttpClientUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Aspect
@Component
public class ControllerInterceptor {
    private static final Log log = LogFactory.get();

    @Pointcut("execution(* com.cweb..controller..*(..)) && " +
            "(@annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) )")
    private void controllerAspect() {
    }

    /**
     * 前置处理
     */
    @Before(value = "controllerAspect()")
    public void beforeService(JoinPoint joinPoint) throws CustomException {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        log.info("---------进入请求处理[{}]---------", request.getRequestURI());
        log.info("请求信息：{}", JSONUtil.parseFromMap(request.getParameterMap()));
        String requestBody = HttpClientUtil.getRequestBody(request);
        if(!StrUtil.isBlank(requestBody)){
            log.info("请求体：{}", requestBody);
        }
    }

    @AfterReturning(returning = "o", pointcut = "controllerAspect()")
    public void afterService(JoinPoint joinPoint, Object o) {
        if (o != null && o instanceof BaseResponse) {
            log.info("返回信息：{}", JSONUtil.toJsonStr(o));
        } else if (o != null && o instanceof Map) {
            log.info("返回信息：{}", JSONUtil.toJsonStr(o));
        } else if (o != null && o instanceof String) {
            log.info("返回信息：{}", o);
        }
        log.info("---------请求处理完成---------");
    }
}
